package codeTop;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class q56 {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals,(a,b)->(a[0]-b[0]));
        int start = intervals[0][0];
        int end = intervals[0][1];
        List<List<Integer>> list = new ArrayList<>();
        for (int i = 1; i < intervals.length; i++) {
            if (end>=intervals[i][0]){
                end = Math.max(end,intervals[i][1]);
            }else {
                list.add(List.of(start,end));
                start = intervals[i][0];
                end = intervals[i][1];
            }
        }
        int[][] res = new int[list.size()+1][2];
        for (int i = 0; i < list.size(); i++) {
            res[i][0] = list.get(i).get(0);
            res[i][1] = list.get(i).get(1);
        }
        res[list.size()][0] = start;
        res[list.size()][1] = end;
        return res;
    }
}
